<template>
  <div class="register-container">
    <h2>用户注册</h2>
    <van-cell-group>
      <van-field
        label="手机号码"
        placeholder="手机号码"
        input-align="left"
        v-model="手机号码"
      ></van-field>
      <van-field
        label="验证码"
        placeholder="验证码"
        input-align="left"
        v-model="图形验证码"
      >
        <img
          slot="button"
          :src="图形验证码Src"
          @click="获取图形验证码()"
          alt="验证码"
        />
      </van-field>
      <van-cell>
        <van-button
          type="primary"
          block
          plain
          :disabled="disable向用户发送验证码"
          @click="向用户发送短信验证码()"
        >
          <template v-if="disable向用户发送验证码 && smsCooldown > 0">
            {{ `请等待${smsCooldown}秒钟后再发送验证码。` }}
          </template>
          <template v-else>
            获取短信验证码
          </template>
        </van-button>
      </van-cell>

      <van-field
        v-if="isSendSms"
        label="短信验证码"
        placeholder="短信验证码"
        input-align="left"
        v-model="手机短信验证码"
      >
      </van-field>
      <van-cell v-if="isSendSms">
        <van-button
          type="primary"
          block
          :disabled="disable向接口注册"
          @click="向接口注册()"
        >
          注册
        </van-button>
      </van-cell>
    </van-cell-group>

    <br />
    <br /><br />
    <br /><br /><br /><br />

    <van-button @click="缓存token并跳转('aaa')">
      缓存token并跳转
    </van-button>
  </div>
</template>
<script>
import { bus } from '@/main.js';
import { mapState, mapMutations } from 'vuex';
import storage from '@/assets/storage.js';

export default {
  name: 'register',
  mixins: [], //混入
  components: {}, //组件
  props: {}, //集成属性
  data() {
    return {
      客户端唯一识别码: '', // 客户端唯一识别码
      手机号码: '', //用户加密的电话号码
      手机短信验证码: '', // 用户的手机短信验证码
      图形验证码: '',
      图形验证码Src: '',
      isSendSms: false, //是否发送过短信
      smsCooldown: 0, // 短信发送冷却时间（秒）
      maxCooldown: 1,
      fromUserId: '',
    };
  },
  computed: {
    ...mapState([]),
    disable向用户发送验证码: function() {
      let a = this.手机号码.length > 0;
      let b = this.图形验证码.length == 4;
      let c = this.smsCooldown == 0;
      return !(a && b && c);
    },
    disable向接口注册: function() {
      let a = this.手机号码.length > 0;
      let b = this.图形验证码.length == 4;
      let c = this.手机短信验证码.length == 4;
      return !(a && b && c);
    },
    a: function() {
      let arr = [
        this.手机号码,
        this.客户端唯一识别码,
        this.图形验证码,
        this.手机短信验证码,
      ];
      return arr.map((v) => {
        return this.$encryption.encrypt(v);
      });
    },
  },
  methods: {
    ...mapMutations([]),
    unicodeEscapeSequenceToBinary: function(unicodeEscapeString) {
      // 移除字符串中的非Unicode转义序列部分（假设字符串仅包含\uXXXX形式的转义序列）
      // 注意：这个正则表达式假设输入字符串是有效的，并且只包含\uXXXX形式的转义序列
      const unicodeMatches = unicodeEscapeString.match(/\\u([0-9a-fA-F]{4})/g);
      if (!unicodeMatches) {
        throw new Error(
          'Input string does not contain valid Unicode escape sequences.'
        );
      }
      // 创建一个Uint8Array来存储转换后的二进制数据
      const binaryData = new Uint8Array(unicodeMatches.length);
      // 遍历所有匹配项，将\uXXXX转换为对应的字节值
      unicodeMatches.forEach((match, index) => {
        // 提取十六进制数
        const hex = match.slice(2); // 去掉前面的\u
        // 将十六进制数转换为十进制数（即字节值）
        const byteValue = parseInt(hex, 16);
        // 将字节值存储到Uint8Array中
        binaryData[index] = byteValue;
      });
      return binaryData;
    },

    获取图形验证码: function() {
      let p = {
        userVerifyKey: this.客户端唯一识别码,
      };
      this.$api.用户模块
        .获取图形验证码(p)
        .then((res) => {
          // 将 ArrayBuffer 转换为 Blob 对象
          const blob = new Blob([res], { type: 'image/png' });
          // 为 Blob 对象创建一个临时 URL
          this.图形验证码Src = URL.createObjectURL(blob);
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },

    向用户发送短信验证码: function() {
      let _ = this._;
      if (this.smsCooldown > 0) {
        alert('请等待几秒钟后再发送验证码。');
        return;
      }
      let p = {};
      let d = _.mapValues(
        {
          phoneNumber: this.手机号码, //电话号码
          userVerifyKey: this.客户端唯一识别码, //客户端唯一识别码
          userVerifyValue: this.图形验证码, //图形验证码
        },
        (v, k) => {
          if (['userVerifyKey', 'userVerifyValue'].includes(k)) return v;
          return this.$encryption.encrypt(v);
        } //该方法中参数的每个值都需要加密
      );
      this.smsCooldown = this.maxCooldown; // 设置冷却时间
      const countdown = setInterval(() => {
        if (this.smsCooldown <= 0) {
          clearInterval(countdown);
          this.isSendSms = true;
        } else {
          this.smsCooldown--;
        }
      }, 1000);
      this.$api.用户模块
        .用户发送短信验证码(p, d)
        .then((res) => {
          this.isSendSms = true;
        })
        .catch((err) => {
          console.error(err);
          alert('验证码错误或发送失败，请重试。');
        })
        .finally((_) => {});
    },
    向接口注册: function() {
      let p = {};
      let d = _.mapValues(
        {
          phoneNumber: this.手机号码, //用户AES加密的电话号码
          phoneVerifyValue: this.手机短信验证码, //用户的手机短信验证码
        },
        (v) => {
          return this.$encryption.encrypt(v);
        } //该方法中参数的每个值都需要加密
      );
      if (!_.isNull(this.fromUserId)) {
        Object.assign(d, {
          fromUserId: this.fromUserId, //介绍人UserId
        });
      }
      this.$api.用户模块
        .用户注册(p, d)
        .then((res) => {
          alert('注册成功！');
          // 将res.data作为token缓存备用
          // 跳转到登录页面或其他页面
        })
        .catch((err) => {
          console.error(err);
          alert('注册失败，请检查您的输入。');
        })
        .finally((_) => {});
    },
    缓存token并跳转: function(token, url) {
      storage.getLS('token', token);
      let path = this._.get(url, '', '');
      this.$router.push('/index');
    },
  },
  mounted() {
    let urlArgs = this.$getUrlArgs();
    this.fromUserId = this._.get(urlArgs, 'fromUserId', null);
    this.客户端唯一识别码 = this.$getClientUniqueId(); //设置“客户端唯一识别码”
    // 初始化图形验证码
    this.获取图形验证码();
  },
};
</script>
<style lang="less" scoped></style>
